package com.framework.common.exception;

import com.alibaba.fastjson.JSONObject;
import com.framework.common.Enums.FrameworkErrorCodeEnum;
import com.framework.common.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/4/12 16:14
 * @since JDK 1.8
 */
@Component
@Slf4j
public class ResourceAccessDeniedHandler implements AccessDeniedHandler  {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        log.error("访问权限受限！", e);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("text/javascript;charset=utf-8");
        httpServletResponse.getWriter().print(JSONObject.toJSONString(R.error(FrameworkErrorCodeEnum.AUTHORIZATION_FAIL)));
    }
}
